#include "timeutil.h"
#include <ctime>
std::string getCurrentYMD(char delimeter /*= '-'*/)
{
	std::string result;
	time_t now = time(NULL);
	tm* tmNow = localtime(&now);
	char fmtStr[] = {'%', 'Y', delimeter, '%', 'm', delimeter, '%', 'd','\0'};
	char buff[16];

	strftime(buff, 16, fmtStr, tmNow);
	return std::string(buff);
}

std::string getCurrentTime()
{
	std::string result;
	time_t now = time(NULL);
	tm* tmNow = localtime(&now);
	char fmtStr[] = "%Y-%m-%d %H:%M:%S";
	char buff[32];

	strftime(buff, 32, fmtStr, tmNow);
	return std::string(buff);
}

std::string tm2String(tm& tTime)
{
	char buff[32];
	char* fmtStr = "%Y-%m-%d %H:%M:%S";
	strftime(buff, 32, fmtStr, &tTime);
	return std::string(buff);
}



std::string getNextYMD(char delimeter /*= '-'*/)
{
	std::string result;
	time_t now = time(NULL);
	tm* tmNow = localtime(&now);
	tmNow->tm_mday += 1;
	char fmtStr[] = {'%', 'Y', delimeter, '%', 'm', delimeter, '%', 'd','\0'};
	char buff[16];

	strftime(buff, 16, fmtStr, tmNow);
	if(tmNow)
	{
		free(tmNow);
	}
	return std::string(buff);
}

tm string2Tm(std::string sTime)
{
	tm tm1;
	sscanf_s(sTime.c_str(), "%4d-%2d-%2d %2d:%2d:%2d",   
		&tm1.tm_year,
		&tm1.tm_mon,
		&tm1.tm_mday,
		&tm1.tm_hour,
		&tm1.tm_min,
		&tm1.tm_sec);

	tm1.tm_year -= 1900;
	tm1.tm_mon--;
	tm1.tm_isdst=-1;
	tm1.tm_wday = 0;
	return tm1;
}

long getTimeGapToNow(std::string sTime)
{
	tm tm1 = string2Tm(sTime);
	time_t time1 = mktime(&tm1);
	time_t now = time(NULL);

	return time1 - now;
}

std::string secondsToDHMS(long lSeconds /* = 0 */)
{
	if(0 == lSeconds)
	{
		return std::string("0d: 0h, 0m");
	}

	int rest = 0;
	int days = lSeconds / SECONDS_PER_DAY;
	rest = lSeconds % SECONDS_PER_DAY;

	int hours = rest /  SECONDS_PER_HOUR;
	rest = rest % SECONDS_PER_HOUR;

	int minutes = rest / SECONDS_PER_MININUTE;
	rest = rest % SECONDS_PER_MININUTE;
	char buff[32];
	memset(buff, 0, 32);

	sprintf(buff, "%dd, %dh, %dm, %ds", days, hours, minutes, rest);
	return std::string(buff);
}

time_t string2Time(std::string sTime)
{
	if(sTime.empty())
	{
		return 0;
	}
	tm tm1 = string2Tm(sTime);
	time_t time1 = mktime(&tm1);
	return time1;
}

int isTimeInGap(std::string sTime1, std::string sTime2, std::string sTime /* = ""*/)
{
	time_t t1 = string2Time(sTime1);
	time_t t2 = string2Time(sTime2);
	time_t tTime = sTime.empty() ? time(NULL) : string2Time(sTime);

	if(t1 > t2)
	{
		std::swap(t1, t2);
	}

	return tTime > t1 && tTime < t2;
}

std::string time2String(time_t tTime)
{
	return tm2String(*(localtime(&tTime)));
}